package com.quectel.core.module.devicepatrol.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.core.devicepatrol.DevicePatrolEventReportConstants;
import com.quectel.constant.core.devicepatrol.DevicePatrolTaskConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.devicepatrol.dao.DevicePatrolTaskDao;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolEventReportDto;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolPlanDto;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolRouteDeviceDto;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolTaskDto;
import com.quectel.core.module.devicepatrol.entity.DevicePatrolTaskEntity;
import com.quectel.core.module.devicepatrol.service.*;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:08
 */
@DubboService
public class DevicePatrolTaskServiceImpl extends ServiceImpl<DevicePatrolTaskDao, DevicePatrolTaskEntity> implements DevicePatrolTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DevicePatrolTaskServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> DEVICE_PATROL_TASK_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "DEVICE_PATROL_TASK_CACHE_BY_ID:%d", id);

    @Autowired
    private DevicePatrolTaskDao devicePatrolTaskDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private DevicePatrolEventReportService devicePatrolEventReportService;
    @Autowired
    private DevicePatrolPlanService devicePatrolPlanService;
    @Autowired
    private DevicePatrolRouteService devicePatrolRouteService;
    @Autowired
    private DevicePatrolRouteDeviceService devicePatrolRouteDeviceService;


    @Override
    public List<DevicePatrolTaskDto> genDevicePatrolTaskByDate(Date date) {

        //查询可执行的plan
        List<DevicePatrolPlanDto> devicePatrolPlanDtos = devicePatrolPlanService.queryListByDate(date);

        List<DevicePatrolTaskDto> devicePatrolTaskDtos = new ArrayList<>();

        String dateStr = DateUtils.format(date, DateUtils.FormatType.SIMPLE);
        Date createTime = new Date();

        for (DevicePatrolPlanDto planDto : devicePatrolPlanDtos) {

            List<String> dayPeriodArr = JacksonUtils.parseArray(planDto.getDayPeriodArr(), String.class);
            if (CollectionUtils.isEmpty(dayPeriodArr)) {
                continue;
            }

            List<DevicePatrolRouteDeviceDto> devicePatrolRouteDeviceDtos = devicePatrolRouteDeviceService.queryListByRouteId(planDto.getRouteId());
            if (CollectionUtils.isEmpty(devicePatrolRouteDeviceDtos)) {
                continue;
            }

            List<DevicePatrolTaskEntity> devicePatrolTaskEntities = new ArrayList<>();

            for (String dayPeriod : dayPeriodArr) {
                String[] split = dayPeriod.split("-");
                //生成任务开始时间和结束时间
                String execStartTime = String.format(DevicePatrolTaskConstants.EXEC_TIME_TEMPLATE, dateStr, split[0]);
                String execEndTime = String.format(DevicePatrolTaskConstants.EXEC_TIME_TEMPLATE, dateStr, split[1]);
                //根据执行时间生成当天的计划
                DevicePatrolTaskEntity entity = new DevicePatrolTaskEntity();
                entity.setId(Snowflake.nextId());
                entity.setTenantId(planDto.getTenantId());
                entity.setRouteName(planDto.getDevicePatrolRouteName());
                entity.setVillageId(planDto.getVillageId());
                entity.setPlanId(planDto.getId());
                entity.setName(genTaskName(dateStr, planDto.getName(), dayPeriod));
                entity.setExecUserId(planDto.getExecUserId());
                entity.setExecUsername(planDto.getExecUsername());
                entity.setDate(dateStr);
                entity.setPeriod(dayPeriod);
                entity.setExecStartTime(DateUtils.parse(execStartTime, DateUtils.FormatType.COMMON));
                entity.setExecEndTime(DateUtils.parse(execEndTime, DateUtils.FormatType.COMMON));
                entity.setExecStatus(DevicePatrolTaskConstants.TasksStatusEnum.STATUS_UNEXECUTED.getStatus());
                entity.setExecCount(0);
                entity.setRouteCount(devicePatrolRouteDeviceDtos.size());
                entity.setRouteExecTotalStatus(JacksonUtils.toJsonString(new ArrayList<>(0)));
                entity.setIsPushed(DevicePatrolTaskConstants.IsPushedEnum.IS_PUSHED.getIsPushed());
                entity.setCreateTime(createTime);
                devicePatrolTaskEntities.add(entity);
                devicePatrolTaskDtos.add(CopyUtils.copyObj(entity, DevicePatrolTaskDto.class));

                //巡检记录生成
                if (CollectionUtils.isNotEmpty(devicePatrolRouteDeviceDtos)) {
                    List<DevicePatrolEventReportDto> patrolEventReportDtos = new ArrayList<>(entity.getRouteCount());
                    for (DevicePatrolRouteDeviceDto devicePatrolRouteDeviceDto : devicePatrolRouteDeviceDtos) {
                        //提前生成上报记录
                        DevicePatrolEventReportDto reportDto = new DevicePatrolEventReportDto();
                        reportDto.setId(Snowflake.nextId());
                        reportDto.setTenantId(entity.getTenantId());
                        reportDto.setVillageId(entity.getVillageId());
                        reportDto.setTaskId(entity.getId());
                        reportDto.setTaskName(entity.getName());
                        reportDto.setDeviceId(devicePatrolRouteDeviceDto.getDeviceId());
                        reportDto.setReportUserId(entity.getExecUserId());
                        reportDto.setReportUsername(entity.getExecUsername());
                        reportDto.setStatus(DevicePatrolEventReportConstants.ReportStatusEnum.STATUS_UNEXECUTED.getStatus());
                        reportDto.setCreateTime(createTime);
                        patrolEventReportDtos.add(reportDto);
                    }
                    devicePatrolEventReportService.saveBatch(patrolEventReportDtos);
                }

            }
            super.saveBatch(devicePatrolTaskEntities);
        }
        return devicePatrolTaskDtos;
    }

    private String genTaskName(String dateStr, String planName, String dayPeriod) {
        StringBuilder stringBuilder = new StringBuilder(dateStr);
        return stringBuilder.append("-").append(planName).append("-").append(dayPeriod).toString();
    }

    @Override
    public DevicePatrolTaskDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEVICE_PATROL_TASK_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DevicePatrolTaskDto selectById(Long id) {
        DevicePatrolTaskEntity entity = devicePatrolTaskDao.selectById(id);
        DevicePatrolTaskDto devicePatrolTaskDto = paddingField(CopyUtils.copyObj(entity, DevicePatrolTaskDto.class));

        List<Long> deviceIds = new ArrayList<>();

        List<DevicePatrolEventReportDto> devicePatrolEventReportDtos = devicePatrolEventReportService.selectByDevicePatrolTaskId(devicePatrolTaskDto.getId());
        if (CollectionUtils.isNotEmpty(devicePatrolEventReportDtos)) {
            //对上报详情重排序 与巡检路线顺序保持一致
            List<Long> finalDeviceIds = deviceIds;
            devicePatrolEventReportDtos.sort((o1, o2) -> {
                int io1 = finalDeviceIds.indexOf(o1.getDeviceId());
                int io2 = finalDeviceIds.indexOf(o2.getDeviceId());
                return io1 - io2;
            });
        }
        devicePatrolTaskDto.setDevicePatrolEventReportDtos(devicePatrolEventReportDtos);

        return devicePatrolTaskDto;
    }

    @Override
    public List<DevicePatrolTaskDto> queryList(Map<String, Object> params) {
        List<DevicePatrolTaskEntity> list = devicePatrolTaskDao.queryList(params);
        List<DevicePatrolTaskDto> result = CopyUtils.copyList(list, DevicePatrolTaskDto.class);
        result.forEach(this::paddingField);
        return result;
    }


    private DevicePatrolTaskDto paddingField(DevicePatrolTaskDto dto) {
        if (dto != null) {
            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            if (villageDto != null) {
                dto.setVillageName(villageDto.getName());
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return devicePatrolTaskDao.queryTotal(params);
    }

    @Override
    public Long save(DevicePatrolTaskDto dto) {
        DevicePatrolTaskEntity entity = CopyUtils.copyObj(dto, DevicePatrolTaskEntity.class);
        entity.setId(Snowflake.nextId());
        devicePatrolTaskDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(DevicePatrolTaskDto dto) {
        DevicePatrolTaskEntity entity = CopyUtils.copyObj(dto, DevicePatrolTaskEntity.class);
        devicePatrolTaskDao.updateById(entity);
        CacheKit.invalidRedisCache(DEVICE_PATROL_TASK_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(DevicePatrolTaskDto dto) {
        DevicePatrolTaskEntity entity = CopyUtils.copyObj(dto, DevicePatrolTaskEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, devicePatrolTaskDao);

        CacheKit.invalidRedisCache(DEVICE_PATROL_TASK_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        devicePatrolTaskDao.deleteById(id);

        CacheKit.invalidRedisCache(DEVICE_PATROL_TASK_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
